package com.ckerchina.admin.ckadmin.service.sms.util;

import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateUtils;
import org.apache.http.client.fluent.Form;
import org.apache.http.client.fluent.Request;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.ckerchina.admin.ckadmin.service.sms.dto.SmsReceiveReport;
import com.ckerchina.admin.ckadmin.service.sms.dto.SmsSendResult;
import com.ckerchina.admin.ckadmin.service.sms.dto.SmsStatusReport;
import com.ckerchina.admin.ckadmin.utils.XmlUtils;

public class ProgroupSmsUtil {

	private static Logger logger = LoggerFactory.getLogger(ProgroupSmsUtil.class);

	public static SmsSendResult sendMessage(String mobiles, String content, String URL, String userName,
			String password, String userid) {
		if (StringUtils.isBlank(mobiles)) {
			throw new IllegalArgumentException("手机号码为空");
		}
		int iMobiCount = StringUtils.countMatches(mobiles, ",") + 1;
		content = "【诸子】" + content;
		try {
			String result = Request.Post(URL + "/sms.aspx")
					.bodyForm(Form.form().add("action", "send").add("userid", userid).add("account", userName)
							.add("password", password).add("mobile", mobiles).add("content", content)
							.add("sendTime", "").add("taskName", "").add("checkcontent", "0")
							.add("countnumber", iMobiCount + "").add("mobilenumber", iMobiCount + "")
							.add("telephonenumber", "0").build(), Charset.forName("UTF-8"))
					.execute().returnContent().asString();
			logger.debug("Progroup发送短信.result:" + result);
			String rt = StringUtils.substringBetween(result, "<returnstatus>", "</returnstatus>");
			if (rt.equalsIgnoreCase("Faild")) {
				logger.error("Progroup短信发送失败.result:" + result);
				return new SmsSendResult(mobiles, content, false, result);
			}
			String str = StringUtils.substringBetween(result, "<taskID>", "</taskID>");
			return new SmsSendResult(mobiles, content, true, str);
		} catch (Exception e) {
			logger.error("Progroup短信发送异常", e);
			return new SmsSendResult(mobiles, content, false, e.getMessage());
		}
	}

	public static Integer queryBalance(String URL, String userName, String password, String userid) {
		try {
			String result = Request.Post(URL + "/sms.aspx")
					.bodyForm(Form.form().add("action", "overage").add("userid", userid).add("account", userName)
							.add("password", password).build(), Charset.forName("UTF-8"))
					.execute().returnContent().asString();
			logger.debug("Progroup短信查询余额.result:" + result);
			String overageStr = StringUtils.substringBetween(result, "<overage>", "</overage>");
			if (StringUtils.isNotEmpty(overageStr)) {
				Integer overage = Integer.parseInt(overageStr);
				return overage;
			} else {
				String message = StringUtils.substringBetween(result, "<message>", "</message>");
				throw new RuntimeException(message);
			}
		} catch (Exception e) {
			logger.error("Progroup短信查询余额异常", e);
			throw new RuntimeException("短信查询余额异常", e);
		}
	}

	public static List<SmsStatusReport> queryStatusReport(String URL, String userName, String password, String userid) {
		List<SmsStatusReport> reportList = new ArrayList<SmsStatusReport>();
		try {
			String result = Request.Post(URL + "/statusApi.aspx")
					.bodyForm(Form.form().add("action", "query").add("userid", userid).add("account", userName)
							.add("password", password).build(), Charset.forName("UTF-8"))
					.execute().returnContent().asString();
			logger.debug("Progroup发送报告.result:" + result);
			List<Map<String, String>> list = XmlUtils.xml2MapList(result, "//returnsms/statusbox");
			for (Map<String, String> map : list) {
				String taskid = map.get("taskid");
				String errorcode = map.get("errorcode");
				String receivetime = map.get("receivetime");
				Date t = DateUtils.parseDate(receivetime, "yyyy/MM/dd hh:mm:ss");
				SmsStatusReport report = new SmsStatusReport(t, taskid, errorcode);
				reportList.add(report);
			}
		} catch (Exception e) {
			logger.error("Progroup短信状态报告异常", e);
			throw new RuntimeException("Progroup短信状态报告异常", e);
		}
		return reportList;
	}

	public static List<SmsReceiveReport> receiveMessage(String URL, String userName, String password, String userid) {
		List<SmsReceiveReport> reportList = new ArrayList<SmsReceiveReport>();
		try {
			String result = Request.Post(URL + "/callApi.aspx")
					.bodyForm(Form.form().add("action", "query").add("userid", userid).add("account", userName)
							.add("password", password).build(), Charset.forName("UTF-8"))
					.execute().returnContent().asString();
			logger.debug("Progroup上行短信查询.result:" + result);
			List<Map<String, String>> list = XmlUtils.xml2MapList(result, "//returnsms/callbox");
			for (Map<String, String> map : list) {
				String mobile = map.get("mobile");
				String content = map.get("content");
				String receivetime = map.get("receivetime");
				Date receiveDate = DateUtils.parseDate(receivetime, "yyyy/MM/dd hh:mm:ss");
				SmsReceiveReport report = new SmsReceiveReport(receiveDate, mobile, content);
				reportList.add(report);
			}
		} catch (Exception e) {
			logger.error("Progroup短信上行信息异常", e);
			throw new RuntimeException("Progroup短信上行信息异常", e);
		}
		return reportList;
	}

	public static SmsSendResult sendVMS(String mobiles, String vmsText, String callerNumber, String URL,
			String userName, String password, String userid) {
		if (StringUtils.isBlank(mobiles)) {
			throw new IllegalArgumentException("手机号码为空");
		}
		try {
			String result = Request.Post(URL + "/vms.ashx")
					.bodyForm(Form.form().add("action", "audio").add("userid", userid).add("account", userName)
							.add("password", password).add("callerNumber", callerNumber).add("vmsText", vmsText)
							.add("destNumbers", mobiles).build(), Charset.forName("UTF-8"))
					.execute().returnContent().asString();
			logger.debug("Progroup发送语音验证码.result:" + result);
			String[] split = result.split("\\|");
			String code = split[0];
			if (code.equals("0")) {
				return new SmsSendResult(mobiles, vmsText, true, split[1]);
			} else {
				logger.error("Progroup语音验证码发送失败.result:" + result);
				return new SmsSendResult(mobiles, vmsText, false, split[1]);
			}
		} catch (Exception e) {
			logger.error("Progroup语音验证码发送异常", e);
			return new SmsSendResult(mobiles, vmsText, false, e.getMessage());
		}
	}

	public static List<SmsStatusReport> queryVMSStatusReport(String URL, String userName, String password,
			String userid) {
		List<SmsStatusReport> reportList = new ArrayList<SmsStatusReport>();
		try {
			String result = Request.Post(URL + "/vms.ashx")
					.bodyForm(Form.form().add("action", "report").add("userid", userid).add("account", userName)
							.add("password", password).build(), Charset.forName("UTF-8"))
					.execute().returnContent().asString();
			logger.debug("Progroup语音验证码发送报告.result:" + result);
			List<Map<String, String>> list = XmlUtils.xml2MapList(result, "//result/callbox");
			for (Map<String, String> map : list) {
				String taskid = map.get("batchId");
				String errorcode = map.get("status");
				String holdTime = map.get("holdTime");
				String receivetime = map.get("startTime");
				Date startDate = DateUtils.parseDate(receivetime, "yyyy-MM-dd hh:mm:ss");
				String endTime = map.get("endTime");
				Date endDate = DateUtils.parseDate(endTime, "yyyy-MM-dd hh:mm:ss");
				SmsStatusReport report = new SmsStatusReport(startDate, taskid, errorcode, endDate, holdTime);
				reportList.add(report);
			}
		} catch (Exception e) {
			logger.error("Progroup语音验证码报告异常", e);
			throw new RuntimeException("Progroup短信状态报告异常", e);
		}
		return reportList;
	}

}
